package cn.didi.feidi.androidorder.adapter;

import android.databinding.DataBindingUtil;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.assembly.DeleteGoodsFragmentDialog;
import cn.didi.feidi.androidorder.databinding.ItemHomePageRecyclerViewBinding;
import cn.didi.feidi.androidorder.db.ShoppingCarDao;
import cn.didi.feidi.androidorder.model.ShoppingCar;
import cn.didi.feidi.androidorder.model.WaterBucket;

/**
 * Created by jinxiong on 2017/8/24.
 */

public class PersonalCollectionsRecyclerViewAdapter extends RecyclerView.Adapter<PersonalCollectionsRecyclerViewAdapter.ViewHolder> {


    private FragmentActivity activity;
    private ArrayList<WaterBucket> collections;
    private AsyncSession asyncSession;
    private Fragment fragment;


    public PersonalCollectionsRecyclerViewAdapter(Fragment fragment) {
        this.activity = fragment.getActivity();
        this.fragment = fragment;
        collections = new ArrayList<>();
        asyncSession = OrderApplication.getDaoSession().startAsyncSession();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        ItemHomePageRecyclerViewBinding binding = DataBindingUtil.inflate(activity.getLayoutInflater(),
                R.layout.item_home_page_recycler_view, parent, false);

        ViewHolder viewHolder = new ViewHolder(binding.getRoot());

        viewHolder.setBinding(binding);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {

        if (collections.size() == 0) {
            return;
        }

        ItemHomePageRecyclerViewBinding binding = holder.getBinding();

        binding.setWaterBucket(collections.get(position));

        Glide.with(fragment)
                .load(collections.get(position).getPicUrl())
                .placeholder(R.drawable.logo)
                .into(binding.waterBucketIv);

        addListener(holder, position, binding);


    }

    private void addListener(ViewHolder holder, final int position, ItemHomePageRecyclerViewBinding binding) {


        binding.itemHomePageCollectTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final DeleteGoodsFragmentDialog dialog = new DeleteGoodsFragmentDialog();
                dialog.setTitle("取消收藏此商品?");
                dialog.setLeftMessage("狠心取消");


                dialog.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();

                        asyncSession.setListenerMainThread(new AsyncOperationListener() {
                            @Override
                            public void onAsyncOperationCompleted(AsyncOperation operation) {

                                if (operation.isFailed()) {
                                    Toast.makeText(activity, "取消失败", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                                Toast.makeText(activity, "成功取消", Toast.LENGTH_SHORT).show();
                                collections.remove(operation.getParameter());
                                notifyDataSetChanged();
                            }
                        });

                        asyncSession.delete(collections.get(position));
                    }
                });

                dialog.show(activity.getSupportFragmentManager(), "");

            }
        });

        holder.getBinding().itemHomePageAddShoppingCarLl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final ShoppingCar shoppingCar = new ShoppingCar();
                shoppingCar.convertData(collections.get(position));


                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                    @Override
                    public void onAsyncOperationCompleted(AsyncOperation operation) {


                        if (operation.isFailed()) {
                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (operation.getType() == AsyncOperation.OperationType.QueryUnique) {

                            if (operation.getResult() == null) {
                                shoppingCar.setBuyCount(1);

                                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                    @Override
                                    public void onAsyncOperationCompleted(AsyncOperation operation) {
                                        if (!operation.isFailed()) {
                                            Toast.makeText(activity, "成功加入购物车 ", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });

                                asyncSession.insert(shoppingCar);

                            } else {

                                ShoppingCar shopCar = (ShoppingCar) operation.getResult();
                                shopCar.setBuyCount(shopCar.getBuyCount() + 1);

                                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                                    @Override
                                    public void onAsyncOperationCompleted(AsyncOperation operation) {

                                        if (!operation.isFailed()) {
                                            Toast.makeText(activity, "成功加入购物车 ", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(activity, "加入购物车失败", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });


                                asyncSession.update(shopCar);
                            }
                        }
                    }


                });

                asyncSession.queryUnique(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(ShoppingCar.class))
                        .where(ShoppingCarDao.Properties.BucketTypeId.eq(shoppingCar.getBucketTypeId()))
                        .build());

            }
        });
    }

    @Override
    public int getItemCount() {
        return collections.size();
    }

    public void setCollections(ArrayList<WaterBucket> collections) {

        this.collections.clear();
        if (collections != null) {
            this.collections.addAll(collections);
        }
        notifyDataSetChanged();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private ItemHomePageRecyclerViewBinding binding;

        public ViewHolder(View itemView) {
            super(itemView);
        }

        public ItemHomePageRecyclerViewBinding getBinding() {
            return binding;
        }

        public void setBinding(ItemHomePageRecyclerViewBinding binding) {
            this.binding = binding;
        }
    }
}

